#!/bin/bash

# Version script for Marathon.
#
# Change MINOR to x+1 and BRANCH_POINT to commit hash of common ancestor of master and releases/1.x
# after a releases/1.x was cut
MAJOR=1
MINOR=11
BRANCH_POINT=0513cddcac83bd4082d48098d489e69686695998
PREVIOUS_BRANCH=origin/releases/1.$(($MINOR - 1))
REF=HEAD

declare -a OTHERARGS
help() {
  cat <<-EOF
Usage $0 [options]

  --help This help
  --ref  The reference for which version to output Defaults to HEAD

Non-arg params

* commit - output just the formatted commit hash
* docker - output the version as used by the Docker tag
* package - output the version with the commit hash, ie 1.9.34-a122edcb4

EOF
}

while ! [ -z "$1" ]; do
  arg="$1"
  shift
  case "$arg" in
    --help)
      help
      exit 0
      ;;
    --ref)
      REF="$1"
      shift
      ;;
    *)
      OTHERARGS+=("$arg")
      ;;
  esac
done

# Infer version
# Number of commits since branch point
IS_DIRECT_CHILD=$( git log origin/master..$BRANCH_POINT)
COMMIT_NUMBER="$(git rev-list --count --first-parent $BRANCH_POINT..$REF)"
COMMIT_HASH=$(git rev-parse --short $REF)

# Detect if the commit in question belongs to another minor version
if !(git merge-base --is-ancestor $BRANCH_POINT $REF) || (git merge-base --is-ancestor $REF $PREVIOUS_BRANCH) &&
      [ $(git rev-parse --verify $REF) != $(git rev-parse --verify $BRANCH_POINT) ]; then
  echo "$REF is not a ${MAJOR}.${MINOR}.x version"
  exit 1
fi

case ${OTHERARGS[0]} in
  commit)
    # Echo commit hash
    echo "$COMMIT_HASH"
    ;;
  package)
    # Echo package version plus hash
    echo "$MAJOR.$MINOR.$COMMIT_NUMBER-$COMMIT_HASH"
    ;;
  docker)
    # Version for Docker image, e.g. v1.7.42
    echo "v$MAJOR.$MINOR.$COMMIT_NUMBER"
    ;;
  "")
    # Echo version
    # E.g. 1.7.42
    echo "$MAJOR.$MINOR.$COMMIT_NUMBER"
    ;;
  *)
    echo "ERROR: ${OTHERARGS[0]} is not a version format"
    echo
    help
    exit 1
    ;;


esac
